// 引入Room集合
const { Room } = require('../modle/lsh_Room')
const path = require('path')
const fs = require('fs')
let name = null;
// 图片加入
function photos(req, res, next) {
  req.files.forEach(f => {
    let max = 9999;
    let min = 1000;
    // 拼接一个新的文件名：毫秒数+随机数+后缀名
    let t = Date.now();
    let n = parseInt(Math.random() * (max - min) + min);
    let z = path.extname(f.originalname);// 获取文件的后缀名
    name = '' + t + n + z;
    // 2.读取原始文件
    let data = fs.readFileSync(f.path)
    // 3.将文件写入指定的文件夹
    fs.writeFile(path.resolve(__dirname,'../public/images', name), data, function (err) {
      if (err) {
        console.log('错误：' + err);
      }
    })
    res.send(path.resolve(__dirname, '../public/images', name))
  })
  return name
}

// 添加到数据库
function upstudents(phone, name, sex, my_name) {
  var codition = { phone }
  var options = { avatar: name, gender: sex, name: my_name }
  Room.update(codition, options, function (err, res) {
    if (err) {
      console.log(err);
    }
    console.log(res);
  })
}
// 人物其余信息查询
function queryRoom(phone, callback) {
  Room.find(phone, function (err, data) {
    if (err) {
      console.log(err);
    }
    callback(data)
    console.log(data);  
  })
}

module.exports = {
  photos,
  upstudents,
  queryRoom
}